import { NextRequest, NextResponse } from 'next/server';
import { getHardwareInfo, generateHardwareHash, generateLicense } from '@/utils/licenseUtils';

interface LicenseRequest {
  cpuId: string;
  cpuName: string;
  macAddress: string;
  publicIp?: string;
  expiryDate: string;
  admin: boolean;
}

/**
 * 获取硬件信息
 */
export async function GET() {
  try {
    // 并行获取所有硬件信息
    const { cpuId, cpuName, macAddress } = getHardwareInfo();

    return NextResponse.json({
        status: 200,
        message: '硬件信息获取成功',
        data: {
          cpuId,
          cpuName,
          macAddress
        }
      }, { status: 200 });
  } catch (error) {
    console.error('获取硬件信息失败:', error);
    return NextResponse.json({
      status: 500,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}

/**
 * 生成License
 */
export async function POST(request: NextRequest) {
  try {
    const body: LicenseRequest = await request.json();
    
    // 参数验证
    if (!body.cpuId || !body.macAddress || !body.expiryDate) {
      return NextResponse.json({
        status: 400,
        message: 'CPU ID、MAC地址和过期日期为必填项'
      }, { status: 400 });
    }

    // 生成硬件指纹
    const hardwareHash = generateHardwareHash(body.cpuId, body.macAddress, body.cpuName, body.publicIp);

    // 读取私钥
    try {
      const license = generateLicense(hardwareHash, body.expiryDate, body.admin);

      // 返回License数据
      return NextResponse.json({
        status: 200,
        message: 'License生成成功',
        data: license
      }, { status: 200 });
    } catch (error) {
      console.error('读取私钥或签名失败:', error);
      return NextResponse.json({
        status: 500,
        message: '读取私钥或签名失败，请确保私钥文件存在'
      }, { status: 500 });
    }
  } catch (error) {
    console.error('生成License失败:', error);
    return NextResponse.json({
      status: 500,
      message: '服务器内部错误',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}